Using Comparison and Relational Operators in Python
Course: Python Programming
Topic: Using Comparison and Relational Operators
Course Link: Python Training Course – JustAcademy
Demo Link: Register for a Free Course Demo
Website: JustAcademy Official Website
1. Introduction to Comparison and Relational Operators
Comparison operators are fundamental components of Python programming. They allow developers to compare two values, variables, or expressions and determine the relationship between them. These operators help a program make decisions based on conditions.
For example, a program can use comparison operators to check whether a student has passed an examination, whether an employee's salary exceeds a specified amount, whether a user is old enough to register for a service, or whether two values are equal.
In Python, comparison operations generally produce Boolean results: True or False. These results can be used in conditional statements, loops, validation logic, filtering, and other programming tasks.
age = 22
minimum_age = 18
print(age >= minimum_age)
print(age == minimum_age)
print(age < minimum_age)
Output:
True
False
False
In this example, Python checks whether the age is at least 18, exactly 18, and below 18. Each expression returns a Boolean result.
2. Learning Objectives
After studying this topic, learners should be able to:
- Understand the purpose of comparison and relational operators.
- Identify all six standard value-comparison operators in Python.
- Compare numeric values, strings, and supported collections.
- Understand the difference between equality and inequality.
- Use comparison operators in conditional statements and loops.
- Combine comparisons with logical operators.
- Write chained comparisons to check multiple conditions.
- Identify common comparison errors and correct them.
- Apply comparisons to real-world programming scenarios.
3. What Are Relational Operators?
Relational operators determine the relationship between two operands. An operand is a value, variable, or expression on which an operator acts.
For example, in 15 > 10, the values 15 and 10 are operands, and > is the relational operator.
Since 15 is greater than 10, the expression evaluates to True.
first_number = 15
second_number = 10
result = first_number > second_number
print(result)
Output:
True
Relational operators are commonly used to implement business rules, eligibility checks, range validation, and decision-making logic.
4. Types of Comparison Operators in Python
Python provides six standard value-comparison operators. They are used to test equality, inequality, and ordering relationships.
| Operator |
Name |
Description |
Example |
Result |
== |
Equal to |
Checks whether two values are equal. |
10 == 10 |
True |
!= |
Not equal to |
Checks whether two values are different. |
10 != 5 |
True |
> |
Greater than |
Checks whether the left value is greater than the right value. |
15 > 10 |
True |
< |
Less than |
Checks whether the left value is smaller than the right value. |
5 < 10 |
True |
>= |
Greater than or equal to |
Checks whether the left value is greater than or equal to the right value. |
10 >= 10 |
True |
<= |
Less than or equal to |
Checks whether the left value is smaller than or equal to the right value. |
8 <= 10 |
True |
5. Equal To Operator (==)
The equal-to operator, represented by ==, checks whether two values are equal. It returns True when the values compare as equal and False otherwise.
This operator is useful for checking usernames, matching values, validating answers, and comparing numerical results.
number1 = 25
number2 = 25
number3 = 30
print(number1 == number2)
print(number1 == number3)
Output:
True
False
Example: Checking a Login Username
stored_username = "admin"
entered_username = "admin"
if entered_username == stored_username:
print("Username matched")
else:
print("Invalid username")
Output:
Username matched
Important: The == operator compares values. It is different from the assignment operator =, which assigns a value to a variable.
score = 80 # Assignment
print(score == 80) # Comparison
Output:
True
6. Not Equal To Operator (!=)
The not-equal-to operator, represented by !=, checks whether two values are different. It returns True when the values are not equal and False when they are equal.
password = "python123"
entered_password = "python456"
print(password != entered_password)
Output:
True
Example: Validating a Status
status = "inactive"
if status != "active":
print("Account is not active")
else:
print("Account is active")
Output:
Account is not active
This operator is useful when a program needs to detect mismatched values, reject invalid input, or execute a block of code only when a condition is not satisfied.
7. Greater Than Operator (>)
The greater-than operator checks whether the value on the left is strictly greater than the value on the right. Equality does not satisfy this condition.
salary = 50000
minimum_salary = 40000
print(salary > minimum_salary)
print(minimum_salary > salary)
Output:
True
False
Example: Checking Sales Performance
sales = 75000
target = 60000
if sales > target:
print("Sales target exceeded")
else:
print("Sales target not exceeded")
Output:
Sales target exceeded
Use > when a value must exceed a threshold, such as a sales target, minimum balance requirement, or performance benchmark.
8. Less Than Operator (<)
The less-than operator checks whether the left operand is strictly smaller than the right operand. If both values are equal, the result is False.
temperature = 15
limit = 20
print(temperature < limit)
print(temperature < 10)
Output:
True
False
Example: Checking Inventory
stock = 4
reorder_level = 10
if stock < reorder_level:
print("Restock required")
else:
print("Stock level is sufficient")
Output:
Restock required
The less-than operator is commonly used in inventory management, temperature monitoring, loop conditions, and threshold-based validation.
9. Greater Than or Equal To Operator (>=)
The greater-than-or-equal-to operator checks whether the left operand is greater than or equal to the right operand. It returns True in either case.
marks = 40
passing_marks = 40
print(marks >= passing_marks)
print(45 >= passing_marks)
print(30 >= passing_marks)
Output:
True
True
False
Example: Exam Eligibility
marks = 68
passing_marks = 40
if marks >= passing_marks:
print("Student passed")
else:
print("Student failed")
Output:
Student passed
This operator is especially useful for eligibility checks where the boundary value must also be accepted.
10. Less Than or Equal To Operator (<=)
The less-than-or-equal-to operator checks whether the left operand is smaller than or equal to the right operand.
items = 5
maximum_items = 5
print(items <= maximum_items)
print(3 <= maximum_items)
print(8 <= maximum_items)
Output:
True
True
False
Example: Checking a Spending Limit
purchase_amount = 450
budget_limit = 500
if purchase_amount <= budget_limit:
print("Purchase is within budget")
else:
print("Budget exceeded")
Output:
Purchase is within budget
Use this operator when a value must remain below a maximum allowed limit, including budget limits, maximum capacity, and allowed attempt counts.
11. Comparing Numeric Values
Python supports comparison operations on compatible numeric values, including integers and floating-point numbers. Comparisons between numeric types can work even when the types differ.
integer_value = 10
float_value = 10.0
print(integer_value == float_value)
print(12 > 7.5)
print(4.5 < 5)
print(20 != 15)
Output:
True
True
True
True
In the first expression, the integer 10 and floating-point value 10.0 compare as equal numerically.
Working with Decimal Values
Floating-point calculations can sometimes produce small precision differences because many decimal fractions cannot be represented exactly in binary floating-point format.
result = 0.1 + 0.2
print(result)
print(result == 0.3)
Typical output:
0.30000000000000004
False
For approximate floating-point comparisons, use a tolerance when appropriate.
import math
result = 0.1 + 0.2
print(math.isclose(result, 0.3))
Output:
True
12. Comparing Strings
Python supports equality and ordering comparisons for strings. String ordering is lexicographical and is based on Unicode code points, not dictionary rules or language-specific alphabetical conventions.
String comparisons are case-sensitive. Therefore, uppercase and lowercase characters can produce different results.
name1 = "Python"
name2 = "Python"
name3 = "python"
print(name1 == name2)
print(name1 == name3)
print("apple" < "banana")
Output:
True
False
True
Case-Insensitive Comparisons
If a task requires case-insensitive matching, normalize the strings before comparing them.
username1 = "Admin"
username2 = "admin"
print(username1.lower() == username2.lower())
Output:
True
For user-facing text, consider whether whitespace, Unicode normalization, or language-specific sorting rules also need to be handled.
13. Comparing Lists and Tuples
Lists and tuples can be compared for equality. Two lists compare equal when they contain equal corresponding elements in the same order. A list and a tuple with the same visible elements do not compare equal because they are different types.
list1 = [10, 20, 30]
list2 = [10, 20, 30]
list3 = [30, 20, 10]
print(list1 == list2)
print(list1 == list3)
print([1, 2] == (1, 2))
Output:
True
False
False
Lists and tuples also support lexicographical ordering when their corresponding elements support ordering comparisons.
print([1, 2, 3] < [1, 2, 4])
print([1, 2] < [1, 2, 0])
Output:
True
True
Python compares elements from left to right. When it finds the first unequal pair, that comparison determines the ordering. If all shared elements are equal, the shorter sequence is ordered before the longer one.
14. Using Comparison Operators with Conditional Statements
Comparison operators are frequently used with if, elif, and else statements. They allow a program to execute different code depending on whether a condition evaluates to true or false.
Example: Grade Classification
marks = 82
if marks >= 90:
print("Grade A+")
elif marks >= 80:
print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 40:
print("Grade C")
else:
print("Fail")
Output:
Grade A
Python checks the conditions from top to bottom and executes the first matching branch. The order of conditions matters when the ranges overlap.
15. Combining Comparisons with Logical Operators
Logical operators can combine comparison expressions to represent more complex conditions.
| Operator |
Purpose |
Example |
and |
Requires both conditions to be true. |
age >= 18 and age <= 60 |
or |
Requires at least one condition to be true. |
marks < 40 or attendance < 75 |
not |
Negates a Boolean condition. |
not (age >= 18) |
Example: Eligibility Check
age = 25
has_id = True
if age >= 18 and has_id:
print("Eligible to register")
else:
print("Not eligible to register")
Output:
Eligible to register
Logical operators are useful when a rule depends on multiple requirements, such as age, documentation, income, or attendance.
16. Chained Comparisons
Python allows multiple comparison operators to be chained in one expression. This feature is particularly useful for checking whether a value lies within a range.
age = 25
print(18 <= age <= 60)
Output:
True
The expression 18 <= age <= 60 checks both that the age is at least 18 and that it is at most 60. It is equivalent in meaning to 18 <= age and age <= 60, with the middle expression evaluated only once.
More Examples
number = 15
print(10 < number < 20)
print(1 < number < 10)
print(5 <= number <= 15)
Output:
True
False
True
Chained comparisons improve readability when checking numerical ranges and boundaries.
17. Comparison Operators in Loops
Comparison expressions can control when a loop continues or stops. They are often used in while loops and in conditional statements inside for loops.
Example: While Loop
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
The loop continues while count <= 5 evaluates to True. Once the condition becomes false, the loop terminates.
Example: Filtering Values
numbers = [5, 12, 18, 3, 25, 9]
for number in numbers:
if number > 10:
print(number)
Output:
12
18
25
18. Comparison Operators and User Input
The input() function returns text as a string. If you want to compare entered numbers numerically, convert the input into an appropriate numeric type first.
Incorrect Approach
age = input("Enter your age: ")
print(age >= 18)
This code raises a TypeError because it attempts to compare a string with an integer.
Correct Approach
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult")
else:
print("You are under 18")
For robust programs, validate user input and handle invalid values. For example, converting non-numeric text with int() raises a ValueError.
19. Difference Between == and is
The equality operator == compares values, whereas the identity operator is checks whether two references point to the same object.
first = [1, 2, 3]
second = [1, 2, 3]
third = first
print(first == second)
print(first is second)
print(first is third)
Output:
True
False
True
The two separately created lists contain equal values, but they are distinct objects. The variable third refers to the same object as first.
Best practice: Use == for value equality. Use is when identity is what matters, particularly when checking for None.
result = None
if result is None:
print("No result available")
Output:
No result available
20. Common Mistakes When Using Comparison Operators
| Mistake |
Problem |
Correct Approach |
Using = instead of == |
Assignment is not an equality comparison. |
Use value == 10 to compare. |
| Comparing a string with an integer using ordering operators |
Unsupported comparisons raise TypeError. |
Convert the input to a suitable numeric type. |
| Ignoring case in string comparisons |
Strings with different letter cases may not compare equal. |
Normalize case when appropriate. |
Using > when the boundary should be accepted |
A value equal to the threshold returns false. |
Use >= if equality is allowed. |
Using is instead of == |
Identity and equality test different things. |
Use == for ordinary value comparisons. |
| Comparing floating-point results for exact equality |
Rounding effects can produce unexpected results. |
Use a tolerance or math.isclose() where appropriate. |
| Writing overlapping conditions in the wrong order |
An earlier branch can capture values intended for a later branch. |
Arrange conditional branches carefully. |
21. Practical Real-World Examples
Example 1: ATM Withdrawal
balance = 5000
withdrawal = 2000
if withdrawal > 0 and withdrawal <= balance:
balance -= withdrawal
print("Withdrawal successful")
print("Remaining balance:", balance)
else:
print("Invalid withdrawal")
Output:
Withdrawal successful
Remaining balance: 3000
Example 2: Discount Eligibility
purchase_amount = 2500
if purchase_amount >= 2000:
print("You qualify for a discount")
else:
print("No discount available")
Output:
You qualify for a discount
Example 3: Temperature Monitoring
temperature = 42
if temperature > 40:
print("High temperature warning")
elif temperature < 10:
print("Low temperature warning")
else:
print("Temperature is within the expected range")
Output:
High temperature warning
Example 4: Password Length Validation
password = "python123"
if len(password) >= 8:
print("Password length is acceptable")
else:
print("Password must contain at least 8 characters")
Output:
Password length is acceptable
This example checks only password length. A production authentication system should also follow appropriate password-security practices.
22. Practice Exercises
Complete the following exercises to strengthen your understanding of comparison and relational operators.
- Write a program to compare two integers and display whether they are equal.
- Write a program that checks whether a number is greater than 100.
- Write a program that determines whether a student has passed with at least 40 marks.
- Compare two strings and display whether they match exactly.
- Write a program that checks whether a number lies between 1 and 100, inclusive.
- Write a program to check whether a shopping amount qualifies for a discount.
- Use a
while loop to print numbers from 1 to 10.
- Write a program that checks whether an entered age is within the range of 18 to 60.
- Compare two lists for equality and explain the output.
- Demonstrate the difference between
== and is using two separate lists.
23. Practice Exercise Solutions
Solution 1: Compare Two Integers
a = 20
b = 20
if a == b:
print("Both numbers are equal")
else:
print("Numbers are different")
Solution 2: Check a Number Greater Than 100
number = 150
if number > 100:
print("Number is greater than 100")
else:
print("Number is 100 or less")
Solution 3: Check Passing Marks
marks = 55
if marks >= 40:
print("Pass")
else:
print("Fail")
Solution 4: Compare Strings
text1 = "Python"
text2 = "Python"
print(text1 == text2)
Solution 5: Check a Range
number = 75
if 1 <= number <= 100:
print("Number is within the range")
else:
print("Number is outside the range")
24. Interview Questions and Answers
Q1. What are comparison operators in Python?
Comparison operators compare two values and generally return a Boolean result indicating whether a specified relationship holds.
Q2. What is the difference between == and =?
The == operator checks equality, while = assigns a value to a variable.
Q3. What is the difference between > and >=?
The > operator checks whether the left value is strictly greater. The >= operator also accepts equal values.
Q4. What does the != operator do?
It checks whether two values are not equal.
Q5. What type of result do standard comparison expressions return?
For ordinary built-in value comparisons, the result is a Boolean value: True or False.
Q6. Can strings be compared in Python?
Yes. Strings can be compared for equality and ordering. Ordering follows lexicographical Unicode code-point comparison.
Q7. What is a chained comparison?
A chained comparison combines multiple comparisons, such as 10 <= age <= 60, in a readable expression.
Q8. Why can comparing input with a number cause an error?
The input() function returns a string. Convert it to a suitable numeric type before performing numerical ordering comparisons.
Q9. What is the difference between == and is?
== checks value equality, whereas is checks object identity.
Q10. How are comparison operators used in decision-making?
They evaluate conditions used by if, elif, else, and loops to control program execution.
25. Quick Revision Checklist
== checks equality.
!= checks inequality.
> checks whether the left value is greater.
< checks whether the left value is smaller.
>= checks whether the left value is greater than or equal.
<= checks whether the left value is smaller than or equal.
- Comparison expressions are commonly used in conditions and loops.
- Use
and, or, and not to build compound conditions.
- Use chained comparisons for readable range checks.
- Use
== for value equality and is for object identity.
- Convert user input before comparing it numerically.
- Pay attention to boundaries, data types, and floating-point precision.
26. Conclusion
Comparison and relational operators are essential tools for building meaningful Python programs. They help developers evaluate conditions, compare values, validate user input, filter data, and control program flow.
Understanding the six standard value-comparison operators—==, !=, >, <, >=, and <=—provides a strong foundation for learning conditional statements, loops, logical operators, and more advanced programming concepts.
Regular practice with small programs and real-world examples will help you use these operators confidently and avoid common mistakes.
Learn Python with JustAcademy
Continue learning Python programming concepts and strengthen your practical coding skills through the following resources.